<template>
  <div class="flow-container">
    <div class="layout">
      <!-- 左侧可选项区域 -->
      <div class="sidebar">
        <h3>可拖拽节点</h3>
        <div
          v-for="option in nodeOptions"
          :key="option.type"
          class="draggable-node"
          :data-type="option.type"
          draggable="true"
          @dragstart="onDragStart"
        >
          <div class="node-label">{{ option.label }}</div>
          <div class="node-preview-wrapper">
            <div :class="['inner-shape', option.shapeClass]">
              <div class="label">{{ option.label }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧 Vue Flow 画布 -->
      <div class="flow-area">
        <div class="toolbar">
          <a-button type="primary" @click="addRandomNode">添加随机节点</a-button>
          <a-button type="danger" @click="deleteSelected">删除选中节点</a-button>
          <a-button type="default" @click="exportJson">导出 JSON</a-button>
        </div>

        <VueFlow
          v-model:nodes="nodes"
          v-model:edges="edges"
          :node-types="nodeTypes"
          :default-edge-options="{
            type: 'smoothstep',
            animated: true,
            markerEnd: { type: 'arrowclosed', color: '#ff0000' },
            style: { stroke: '#ff0000', strokeWidth: 2, strokeDasharray: 'none' },
          }"
          :connection-line-style="{ stroke: '#ff0000', strokeWidth: 2, strokeDasharray: 'none' }"
          :fit-view-on-init="true"
          :connectable="true"
          @drop="onDrop"
          @dragover.prevent
          @connect="onConnect"
          @node-click="onNodeClick"
          @node-drag-start="onNodeDragStart"
          @node-drag-stop="onNodeDragStop"
          @pane-click="onPaneClick"
        >
          <Background variant="dots" :gap="20" />
          <Controls />
          <MiniMap />
        </VueFlow>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, markRaw } from 'vue'
import { VueFlow, useVueFlow } from '@vue-flow/core'
import type { NodeTypesObject } from '@vue-flow/core'
import { Background } from '@vue-flow/background'
import { Controls } from '@vue-flow/controls'
import { MiniMap } from '@vue-flow/minimap'
import { message } from 'ant-design-vue'
import DiamondNode from './DiamondNode.vue'
import CircleNode from './CircleNode.vue'
import ImageNode from './ImageNode.vue' // 新增导入
import RoundedRectangleNode from './components/RoundedRectangleNode.vue'
import { editingNodeId } from './ts/store' // 导入共享状态
import '@vue-flow/core/dist/style.css'
import '@vue-flow/core/dist/theme-default.css'
import '../style/node-styles.css'

const nodes = ref([])
const edges = ref<any>([])

const nodeTypes: NodeTypesObject = {
  diamond: markRaw(DiamondNode),
  circle: markRaw(CircleNode),
  image: markRaw(ImageNode),
  roundedRectangle: markRaw(RoundedRectangleNode),
}

const { addNodes, getNodes, deleteElements } = useVueFlow()

const nodeOptions = [
  { type: 'diamond', label: '判断节点', shapeClass: 'node-diamond' },
  { type: 'circle', label: '圆形节点', shapeClass: 'node-circle' },
  { type: 'image', label: '图片节点', shapeClass: 'node-image' }, // 新增图片节点
  { type: 'roundedRectangle', label: '圆角长方形节点', shapeClass: 'node-rounded-rectangle' },
]

// Drag-and-drop handlers
function onDragStart(event: DragEvent) {
  if (event.dataTransfer && event.target instanceof HTMLElement) {
    const type = event.target.dataset.type
    if (type) {
      event.dataTransfer.setData('application/vueflow-node-type', type)
    }
  }
}

function onDrop(event: DragEvent) {
  const type = event.dataTransfer?.getData('application/vueflow-node-type')
  if (!type) return

  const bounds = (event.currentTarget as HTMLElement).getBoundingClientRect()
  const position = {
    x: event.clientX,
    y: event.clientY,
  }

  const label = type === 'diamond' ? '判断节点' : type === 'circle' ? '圆形节点' : '圆角长方形节点'
  addNodes([
    {
      id: `${type}-${Date.now()}`,
      type,
      position,
      data: { label },
    },
  ])
}

// Connection handler
function onConnect(params: any) {
  edges.value = [
    ...edges.value,
    {
      ...params,
      id: `edge-${params.source}-${params.target}`,
      type: 'smoothstep',
      animated: true,
      markerEnd: { type: 'arrowclosed', color: '#ff0000' },
      style: { stroke: '#ff0000', strokeWidth: 2, strokeDasharray: 'none' },
    },
  ]
}

// Node interaction handlers
function onNodeClick(event: any, node: any) {
  nodes.value = nodes.value.map(n => ({
    ...n,
    selected: n.id === node.id ? true : false,
  }))
  // if (node.type === 'circle') {
  //   editingNodeId.value = node.id // 仅对圆形节点启用编辑模式
  // }
}

function onNodeDragStart(event: any, node: any) {
  console.log('Node drag started:', node)
}

function onNodeDragStop(event: any, node: any) {
  console.log('Node drag stopped:', node)
}

function onPaneClick() {
  nodes.value = nodes.value.map(n => ({ ...n, selected: false }))
  editingNodeId.value = null // 退出编辑模式
}

// Add a random node
function addRandomNode() {
  const types = ['diamond', 'circle', 'roundedRectangle']
  const type = types[Math.floor(Math.random() * types.length)]
  const label = type === 'diamond' ? '判断节点' : type === 'circle' ? '圆形节点' : '圆角长方形节点'
  addNodes([
    {
      id: `${type}-${Date.now()}`,
      type,
      position: { x: Math.random() * 500, y: Math.random() * 500 },
      data: { label },
    },
  ])
}

// Delete selected nodes
function deleteSelected() {
  const selectedIds = getNodes.value.filter(n => n.selected).map(n => n.id)
  if (selectedIds.length === 0) {
    message.warning('请先选中一个节点')
    return
  }
  deleteElements({ nodes: selectedIds })
  message.success('节点删除成功')
  editingNodeId.value = null // 退出编辑模式
}

// Export JSON
function exportJson() {
  const json = JSON.stringify({ nodes: nodes.value ,edges: edges.value }, null, 2)
  const blob = new Blob([json], { type: 'application/json' })
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = 'flowchart.json'
  a.click()
  window.URL.revokeObjectURL(url)
  message.success('JSON 文件已导出')
}

// 更新节点标签
function updateNodeLabel(nodeId: string, newLabel: string) {
  nodes.value = nodes.value.map(n =>
    n.id === nodeId ? { ...n, data: { ...n.data, label: newLabel } } : n
  )
  editingNodeId.value = null // 编辑完成后退出编辑模式
}
</script>

<style scoped>
.flow-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.layout {
  display: flex;
  height: 100%;
}

.sidebar {
  width: 200px;
  padding: 10px;
  background: #f5f5f5;
  border-right: 1px solid #ccc;
  overflow-y: auto;
}

.sidebar h3 {
  margin: 0 0 10px;
  font-size: 16px;
}

.draggable-node {
  padding: 8px;
  margin-bottom: 8px;
  background: #fff;
  border: 2px solid #ff0000;
  border-radius: 4px;
  cursor: grab;
  user-select: none;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.node-label {
  font-size: 14px;
}

.node-preview-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}

.inner-shape {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.node-diamond {
  background: #fff;
  border: 2px solid #ff0000;
  transform: rotate(45deg);
}

.node-circle {
  background: #fff;
  border: 2px solid #ff0000;
  border-radius: 50%;
}

.node-rounded-rectangle {
  background: #fff;
  border: 2px solid #ff0000;
  border-radius: 4px;
}

.label {
  font-size: 10px;
  transform: rotate(0deg);
  color: #000;
}

.draggable-node:hover {
  background: #ffebee;
}

.flow-area {
  flex: 1;
  position: relative;
}

.toolbar {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
  padding: 10px;
  background: #f0f0f0;
  border-radius: 4px;
}

:deep(.vue-flow__handle) {
  width: 10px;
  height: 10px;
  background: #ff0000;
  border-radius: 50%;
  cursor: crosshair;
}

:deep(.vue-flow__edge .vue-flow__edge-path) {
  stroke: #ff0000;
  stroke-width: 2;
  fill: none;
  stroke-dasharray: none;
}

:deep(.vue-flow__edge-marker) {
  fill: #ff0000;
  stroke: #ff0000;
}
</style>
